<?php

require 'vendor/autoload.php';

use parallel\Runtime;
use Remoteshell\PhpBotSdk\logger\LoggerRecoder;
use Remoteshell\PhpBotSdk\request_lib\MainHttps;
use Remoteshell\PhpBotSdk\webhook\WebHookAccess;


/*****************************************
 *              启动脚本                  *
 * @author Jason              *
 *****************************************/

set_exception_handler('handleException');
set_error_handler('handleError');

if (!file_exists("user_config.json")) {
    $defaultConfig = json_encode([
        "appid" => "your_app_id",
        "secret" => "your_secret",
        "port" => 9000,
        "path" => "src/public"
    ], JSON_PRETTY_PRINT);
    file_put_contents("user_config.json", $defaultConfig);
    @chmod("user_config.json", 0777);
} else {
    json_decode(file_get_contents("user_config.json"), true);
}

$json = json_decode(file_get_contents("user_config.json"), true);


if (!extension_loaded("ffi")) {
    echo "[CRITICAL] 未查找到FFI扩展！尝试退出脚本！";
    exit;
}

if (!extension_loaded("parallel")) {
    echo "[CRITICAL] 未查找到parallel扩展！尝试退出脚本！";
    exit;
}

if (!extension_loaded("openssl")) {
    echo "[CRITICAL] 未查找到openssl扩展！尝试退出脚本！";
    exit;
}

function handleException($exception)
{
    echo "有一个异常发生： ", $exception->getMessage(), "\n";
    $log = new LoggerRecoder();
    $log->record("critical", "有一个异常发生： " . $exception->getMessage());
}


function handleError($errno, $errstr, $errfile, $errline)
{
    echo "错误发生: [$errno] $errstr - $errfile:$errline\n";
    $log = new LoggerRecoder();
    $log->record("error", "错误发生: [$errno] $errstr - $errfile:$errline");
    return true; // 返回true以阻止PHP的默认错误处理器
}

$log = new \Remoteshell\PhpBotSdk\logger\STDLoggerOut();

if (!file_exists($json['path'] . '/index.php')) {
    mkdir($json['path'], 0777, true);
    $log->record("normal", "您现在已经开启WEB INJECT模式！此模式下不支持插件加载！");
    file_put_contents($json['path'] . "/index.php",
        "<?php 
require '../../vendor/autoload.php'
?>");
}

$log->record("normal", "框架已启动！程序运行在端口: " . $json['port']);
exec("php -S 0.0.0.0:" . $json['port'] . " -t" . $json['path']);
